package com.jielin.handling.util;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import org.springframework.util.StringUtils;


/**
 * Created by T470 on 2018/6/27.
 */

public class HttpClientForJL {




    private HttpClient httpClient=new DefaultHttpClient();

    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true)
            .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .build();
    RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
            .setSocketTimeout(5000)
            .setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000)
            .setProxy(new HttpHost("localhost", 8081)
            )
            .build();






    /**
     * 说明:
     * 编辑工具类时需要处理两种请求 get post
     * 参数介绍:
     * 	定义url:确定访问路径
     * 	定义参数集合map<String,String>,指定参数类型都是String
     * 	定义字符集encode=utf-8
     *
     * 方法介绍:
     * 	工具不同用户的需求,需重载多个方法
     */

    /**
     * 编辑思路:
     * 	1.先判断是否包含参数,如果包含参数应该将参数进行动态拼接
     * 	2.判断是否指定字符集编码,如果没有指定则默认使用utf-8
     * 	3.通过httpClient对象发起http请求
     * 	4.判断返回值是否有效
     * 	5.将结果返回
     *
     * @param uri
     * @param params
     * @param charset
     * @return
     * @throws URISyntaxException
     * @throws IOException
     * @throws ClientProtocolException
     */
    public String doGet(String uri,Map<String,String> params,String charset) throws Exception{

        //1.判断是否含有参数
        URIBuilder builder=new URIBuilder(uri);
        if(!StringUtils.isEmpty(params)){
            for (Map.Entry<String, String> param : params.entrySet()) {
                builder.addParameter(param.getKey(), param.getValue());
            }
            uri=builder.toString();
        }

        //判断字符集编码
        if(StringUtils.isEmpty(charset)){
            charset="utf-8";
        }


        //定义get请求对象
        HttpGet httpGet=new HttpGet(uri);
        httpGet.setConfig(requestConfig);

        //发送请求
        HttpResponse httpResponse = httpClient.execute(httpGet);

        //判断请求是否正确
        if(httpResponse.getStatusLine().getStatusCode()==200){
            //result是远程返回的json数据
            String result=EntityUtils.toString(httpResponse.getEntity(),charset);
            return result;
        }


        return null;
    }

    public String doGet(String uri) throws Exception{
        return doGet(uri, null, null);
    }

    public String doGet(String uri,Map<String,String>params) throws Exception{
        return doGet(uri, params, null);
    }



    /**
     * 1.doPost请求方式与doGet类似
     * 2.post中的参数提交借助于form表单
     *
     * 编码步骤:
     * 	1.定义请求对象httpPost
     * 	2.判断是否含有参数,荣国含有参数需要进行表单的赋值
     * 	3.将form表单的参数赋值给post的请求
     * 	4.
     *
     * @param uri
     * @param params
     * @param charset
     * @return
     * @throws Exception
     */
    public String doPost(String uri,Map<String,String>params,String charset) throws Exception{
        //定义post提交方式
        HttpPost httpPost=new HttpPost(uri);
        if(StringUtils.isEmpty(charset)){
            charset="utf-8";
        }

        if(!StringUtils.isEmpty(params)){
            List<NameValuePair> paramterList=new ArrayList();
            for (Map.Entry<String, String>param : params.entrySet()) {
                paramterList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
            }

            UrlEncodedFormEntity entity=new UrlEncodedFormEntity(paramterList,charset);

            httpPost.setEntity(entity);
        }

        HttpResponse httpResponse = httpClient.execute(httpPost);
        if(httpResponse.getStatusLine().getStatusCode()==200){
            String result=EntityUtils.toString(httpResponse.getEntity(),charset);
            return result;
        }

        return null;
    }


    public String doPost(String uri) throws Exception{
        return doPost(uri, null, null);
    }

    public String doPost(String uri,Map<String,String>params) throws Exception{
        return doPost(uri, params, null);
    }


}
